<template>
  <div class="member-application">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>入团申请</span>
        </div>
      </template>
      
      <!-- 申请状态查询 -->
      <div class="application-status" v-if="hasSubmittedApplication">
        <el-alert 
          :title="applicationStatusText" 
          :type="getApplicationStatusType(applicationStatus)"
          show-icon
        >
         
            <div class="status-info">
              <!-- 显示申请时间 -->
              <p v-if="applicationSubmitTime">申请时间：{{ applicationSubmitTime }}</p>
              <!-- 显示备注信息（包括拒绝原因） -->
              <!-- <p v-if="applicationRemark">备注：{{ applicationRemark }}</p> -->
            </div>
         
        </el-alert>
        
        <!-- 已加入社团时显示退出按钮 - 单独显示以确保始终可见 -->
        <div v-if="applicationStatus === '1'" class="exit-action">
          <el-button type="danger" @click="handleExit" style="margin-top: 15px;">退出社团</el-button>
        </div>
      </div>
      
      <!-- 入团申请说明 -->
      <div class="application-intro">
        <h3>社团介绍</h3>
        <p>我们是一个充满活力的旅游爱好者社团，致力于为热爱旅行的朋友们提供一个交流、分享和共同出行的平台。无论你是喜欢自然风光还是人文景观，无论你是经验丰富的旅行达人还是初次踏上旅程的新手，只要你热爱旅行，我们都欢迎你的加入！</p>
        
        <h3>入团条件</h3>
        <ul>
          <li>热爱旅行，有探索世界的热情</li>
          <li>遵守社团的规章制度，服从社团的安排</li>
          <li>具有团队合作精神，乐于助人</li>
          <li>积极参与社团组织的活动</li>
        </ul>
        
        <h3>团员福利</h3>
        <ul>
          <li>优先参加社团组织的各类旅行活动</li>
          <li>享受社团内部的旅行资源共享</li>
          <li>参与社团内部的技能培训和经验分享会</li>
          <li>认识更多志同道合的旅行爱好者</li>
        </ul>
      </div>
        
        <!-- 申请状态加载中 -->
        <div v-if="isLoadingStatus" class="loading-container">
          <el-empty description="正在获取您的申请状态..." />
        </div>
        
        <!-- 入团申请表单 -->
        <div class="application-form" v-if="(!hasSubmittedApplication || applicationStatus === '2') && !isLoadingStatus">
        <!-- 被拒绝提示 -->
        <el-alert 
          v-if="applicationStatus === '2'" 
          title="拒绝原因" 
          type="error" 
          show-icon
        >
          <p v-if="applicationRemark">{{ applicationRemark }}</p>
            <p>您可以重新提交申请，请根据审核意见完善信息。</p>
        </el-alert>
        
        <!-- 首次申请提示 -->
        <el-alert 
          v-else-if="!hasSubmittedApplication" 
          title="欢迎加入我们的社团！" 
          type="success" 
          show-icon
        >
          <template #desc>
            <p>请填写下方申请表单，提交您的入团申请。我们会尽快审核您的申请并给予回复。</p>
          </template>
        </el-alert>
        <el-form ref="formRef" :model="userInfo" :rules="rules" label-width="120px" style="max-width: 600px;">
          <el-form-item label="姓名" prop="nickName">
            <el-input v-model="userInfo.nickName" placeholder="请输入您的姓名" disabled></el-input>
          </el-form-item>
          
          <el-form-item label="性别" prop="sexy" >
            <el-radio-group v-model="userInfo.sexy" disabled> 
              <el-radio label="male">男</el-radio>
              <el-radio label="female">女</el-radio>
              <el-radio label="secret">保密</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="年龄" prop="age">
            <el-input v-model.number="userInfo.age" type="number" placeholder="请输入您的年龄" disabled></el-input>
          </el-form-item>
          
          <el-form-item label="联系电话" prop="phoneNo">
            <el-input v-model="userInfo.phoneNo" placeholder="请输入您的联系电话" disabled></el-input>
          </el-form-item>
          
          <el-form-item label="电子邮箱" prop="email">
            <el-input v-model="userInfo.email" placeholder="请输入您的电子邮箱" disabled></el-input>
          </el-form-item>
          
          <el-form-item label="所在城市" prop="city">
            <el-input v-model="userInfo.city" placeholder="请输入您所在的城市" disabled></el-input>
          </el-form-item>
          
          <el-form-item label="旅行经历" prop="travelExperience">
            <el-radio-group v-model="userInfo.travelExperience">
              <el-radio label="beginner">初学者（1-3次旅行）</el-radio>
              <el-radio label="intermediate">中级（4-10次旅行）</el-radio>
              <el-radio label="advanced">高级（10次以上旅行）</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="喜欢的旅行类型" prop="preferredTravelTypes">
            <el-checkbox-group v-model="userInfo.preferredTravelTypes">
              <el-checkbox label="nature">自然风光</el-checkbox>
              <el-checkbox label="culture">人文历史</el-checkbox>
              <el-checkbox label="adventure">探险挑战</el-checkbox>
              <el-checkbox label="food">美食之旅</el-checkbox>
              <el-checkbox label="shopping">购物休闲</el-checkbox>
              <el-checkbox label="relaxation">度假放松</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          
          <el-form-item label="自我介绍" prop="bio">
            <el-input v-model="userInfo.bio" disabled type="textarea" placeholder="请简要介绍一下自己"></el-input>
          </el-form-item>
          
          <el-form-item label="加入原因" prop="joinReason">
            <el-input v-model="userInfo.joinReason" type="textarea" placeholder="请说明您为什么想加入我们的社团"></el-input>
          </el-form-item>
          
          <el-form-item>
            <el-link type="primary" v-if="userInfo.nickName==''||userInfo.nickName==null" @click="handleClick">请先完善个人信息</el-link>
            <el-button type="primary" @click="handleSubmit" :loading="loading" :disabled="(userInfo.nickName==''||userInfo.nickName==null)">提交申请</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 已提交申请提示 -->
      <div class="submitted-tip" v-if="hasSubmittedApplication && applicationStatus === '0' && !applicationStatusText">
        <p>您的申请已提交，请耐心等待审核结果。审核结果将通过短信或邮件通知您。</p>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useGlobalStore } from '../store/userInfo'
import { ElMessage, ElMessageBox, ElEmpty } from 'element-plus'
import { joinApply, getStatus, outUs } from '@/request/member.js' 
import router from '@/router'



const store = useGlobalStore()
const userInfo = store.userInfo

// 表单相关
const formRef = ref(null)
const loading = ref(false)

// 表单验证规则
const rules = {
  nickName: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  sexy: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { type: 'number', min: 18, max: 65, message: '年龄必须在 18 到 65 之间', trigger: 'blur' }
  ],
  phoneNo: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入电子邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  city: [
    { required: true, message: '请输入所在城市', trigger: 'blur' }
  ],
  travelExperience: [
    { required: true, message: '请选择旅行经历', trigger: 'change' }
  ],
  preferredTravelTypes: [
    { required: true, message: '请至少选择一种喜欢的旅行类型', trigger: 'change' },
    { type: 'array', min: 1, message: '请至少选择一种喜欢的旅行类型', trigger: 'change' }
  ],
  bio: [
    { required: true, message: '请输入自我介绍', trigger: 'blur' },
    { min: 10, max: 500, message: '自我介绍长度在 10 到 500 个字符', trigger: 'blur' }
  ],
  joinReason: [
    { required: true, message: '请说明加入原因', trigger: 'blur' },
    { min: 10, max: 500, message: '加入原因长度在 10 到 500 个字符', trigger: 'blur' }
  ]
}

// 申请状态（实际应用中应该从服务器获取）
const hasSubmittedApplication = ref(false)
const applicationStatus = ref('') // 0: 待审核, 1: 已通过, 2: 已拒绝
const applicationSubmitTime = ref('')
const applicationRemark = ref('')
const isLoadingStatus = ref(true)

// 获取申请状态文本
const applicationStatusText = ref('')
const getApplicationStatusText = (status) => {
  switch (status) {
    case '0':
      return '您的入团申请正在审核中'
    case '1':
      return '恭喜！您的入团申请已通过'
    case '2':
      return '很遗憾，您的入团申请未通过'
    default:
      return '申请状态未知'
  }
}

const getJoinStatus = async () => {
  isLoadingStatus.value = true
  try {
    const res = await getStatus()
    if (res) {
      hasSubmittedApplication.value = true
      applicationStatus.value = res.status
      // 确保时间数据正确绑定
      applicationSubmitTime.value = res.createTime || ''
      // 确保拒绝原因正确绑定
      applicationRemark.value = res.rsn || ''
      // 设置申请状态文本
      applicationStatusText.value = getApplicationStatusText(applicationStatus.value)
    } else {
      hasSubmittedApplication.value = false
      applicationStatus.value = ''
      applicationSubmitTime.value = ''
      applicationRemark.value = ''
      applicationStatusText.value = ''
    }
  } catch (error) {
    console.error('获取加入状态失败:', error)
    ElMessage.error('获取入团状态失败，请稍后重试')
    // 错误情况下默认设置为未申请状态
    hasSubmittedApplication.value = false
    applicationStatus.value = ''
    applicationSubmitTime.value = ''
    applicationRemark.value = ''
    applicationStatusText.value = ''
  } finally {
    isLoadingStatus.value = false
  }
}

getJoinStatus();

// 提交申请
const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      loading.value = true
      joinApply({info:JSON.stringify(userInfo)}).then(res => {
        ElMessage({ message: '申请提交成功，请等待审核', type: 'success' })
          loading.value = false
          getJoinStatus()
      }).catch(err => {
        loading.value = false
        ElMessage({ message: err.message, type: 'error' })
      })
    }
  })
}

// 重置表单
const handleReset = () => {
  formRef.value.resetFields()
}

// 根据申请状态获取提示类型
const getApplicationStatusType = (status) => {
  switch (status) {
    case '0':
      return 'warning'
    case '1':
      return 'success'
    case '2':
      return 'error'
    default:
      return 'info'
  }
}

// 退出社团
const handleExit = () => {
  // 实际应用中这里应该调用API提交退出申请
  ElMessageBox.confirm(
    '确定要退出社团吗？退出后如需重新加入需要再次提交申请。',
    '确认退出',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      loading.value = true
        outUs().then(res => {
          getJoinStatus()
          loading.value = false
          ElMessage({ message: '您已成功退出社团', type: 'success' })
        }).catch(err => {
          loading.value = false
          ElMessage({ message: err.message, type: 'error' })
        })

    })
    .catch(() => {
      ElMessage({ message: '已取消退出', type: 'info' })
    })
}

// 跳转完善个人信息
const handleClick = () => {
  router.push({ name: 'UserCenter' })
}
</script>

<style scoped>
.member-application {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.application-status {
  margin-bottom: 20px;
}

.status-info {
  margin-top: 10px;
}

.status-info p {
  margin: 5px 0;
}

.exit-action {
      margin-top: 15px;
    }
    
    /* 加载状态样式 */
    .loading-container {
      text-align: center;
      padding: 40px;
      min-height: 200px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    /* 退出按钮样式 - 确保按钮始终可见 */
    .exit-action {
      margin-top: 15px;
      text-align: center;
    }

.application-intro {
  margin-bottom: 30px;
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 8px;
}

.application-intro h3 {
  margin-top: 20px;
  margin-bottom: 10px;
  font-size: 16px;
  color: #333;
}

.application-intro h3:first-child {
  margin-top: 0;
}

.application-intro p {
  margin: 0 0 10px 0;
  color: #666;
  line-height: 1.6;
}

.application-intro ul {
  margin: 0 0 10px 20px;
  color: #666;
}

.application-intro li {
  margin-bottom: 5px;
  line-height: 1.6;
}

.application-form {
  margin-top: 20px;
}

.submitted-tip {
  margin-top: 30px;
  padding: 20px;
  background-color: #e6f7ff;
  border-radius: 8px;
  text-align: center;
  color: #1890ff;
}
</style>